﻿using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MyCommon.Https
{
    public static class RequestIpUtility
    {
        public static string GetRequestIp(this HttpContext context) {
            var ip = SplitCSV(GetHeaderValueAs<string>(context, "X-Forwarded-For")).FirstOrDefault();
            if (string.IsNullOrWhiteSpace(ip)) { 
                ip = SplitCSV(GetHeaderValueAs<string>(context,"X-Real-IP")).FirstOrDefault();
            }
            if (string.IsNullOrWhiteSpace(ip)&&context.Connection?.RemoteIpAddress!=null) { 
               ip = context.Connection?.RemoteIpAddress.ToString();
            }
            if(string.IsNullOrWhiteSpace(ip))
            {
                ip = GetHeaderValueAs<string>(context, "REMOTE_ADDR");
            }
            return ip;
        }

        private static T GetHeaderValueAs<T>(HttpContext context, string headerName) { 
            if(context.Request?.Headers?.TryGetValue(headerName,out var value) ?? false)
            {
                string rawValues = value.ToString();
                if(!string.IsNullOrWhiteSpace(rawValues))
                    return (T)Convert.ChangeType(rawValues, typeof(T));
            }
            return default;
        }

        private static List<string> SplitCSV(string csvList)
        {
            if(string.IsNullOrWhiteSpace(csvList)) return new List<string>();
            return csvList.TrimEnd(',').Split(',').AsEnumerable<string>().Select(i=>i.Trim()).ToList();
        }
    }
}
